//
//  MinePageOpusListViewController.m
//  ShowYork
//
//  Created by hxh on 2021/3/5.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "HomePageUserInfoOpusListViewController.h"
#import "HomePageDetailViewController.h"
#import "WaterFallLayout.h"
#import "MinePageOpusListCell.h"
@interface HomePageUserInfoOpusListViewController ()<WaterFallLayoutDelegate,UICollectionViewDelegate,UICollectionViewDataSource,MinePageOpusListCellDelegate>
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)UIView *noDataView;
@property (nonatomic,strong)UIImageView *noDataImgView;
@property (nonatomic,strong)UILabel *noDateLb;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)UIView *refreshView;
@property (nonatomic,copy)void(^scrollCallback)(UIScrollView *scrollView);
@property (nonatomic,assign)NSInteger page;
@property (nonatomic,assign)NSInteger total;

@end

@implementation HomePageUserInfoOpusListViewController

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationNone;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    
    [self loadDataSource];
}
- (void)setUI{
    
    self.page = 1;

    self.isHideNavBar = YES;
    
    WaterFallLayout *layout = [[WaterFallLayout alloc]init];
    layout.delegate = self;
    layout.minimumLineSpacing = 4.0f;
    layout.minimumInteritemSpacing = 4.0;
    layout.sectionInset = UIEdgeInsetsMake(12.0, 4, 0, 4);

    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[MinePageOpusListCell class] forCellWithReuseIdentifier:@"MinePageOpusListCell"];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    __weak typeof(self)weakSelf = self;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page++;
        [weakSelf loadDataSource];
    }];
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.hidden = YES;
    self.collectionView.mj_footer = footer;
    
    self.noDataView = [[UIView alloc]init];
    self.noDataView.backgroundColor = [UIColor whiteColor];
    self.noDataView.hidden = YES;
    [self.view addSubview:self.noDataView];
    
    [self.noDataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
   
    self.noDataImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"mine_noList_tag"]];
    [self.noDataView addSubview:self.noDataImgView];
    
    [self.noDataImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view).offset(-kNavBarHeight - 50);
        make.centerX.equalTo(self.view);
    }];
    
    self.noDateLb = [[UILabel alloc]init];
    self.noDateLb.text = @"无内容";
    self.noDateLb.textColor = C153;
    self.noDateLb.font = font(12);
    self.noDateLb.textAlignment = NSTextAlignmentCenter;
    [self.noDataView addSubview:self.noDateLb];
    [self.noDateLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.noDataView);
        make.top.equalTo(self.noDataImgView.mas_bottom).offset(12);
    }];
   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteHomePageItem:) name:@"deleteHomePageItem" object:nil];
    
    UIView *v2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
    v2.backgroundColor = RGBA(248, 248, 248, 1);
    
    UIView *v3 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 120)];
    v3.backgroundColor = [UIColor whiteColor];
    
    self.refreshView = v3;
    
    [v2 addSubview:v3];

    v2.layer.zPosition = -2;
    self.collectionView.backgroundView = v2;
    

    UIView *v = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 120)];
    v.layer.zPosition = -1;
    v.userInteractionEnabled = NO;
    CAGradientLayer *leftLayer = [CAGradientLayer layer];
    leftLayer.frame = v.bounds;
    leftLayer.colors = @[(id)RGBA(255, 255, 255, 1).CGColor,(id)RGBA(248, 248, 248, 1).CGColor];
    [v.layer addSublayer:leftLayer];
    
    
    [self.collectionView insertSubview:v atIndex:0];
    self.collectionView.backgroundColor = RGBA(248, 248, 248, 1);
}

- (void)deleteHomePageItem:(NSNotification *)note{
    HomePageItemModel *itemModel = note.userInfo[@"data"];
    __block NSInteger index = -1;
    [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.postId isEqualToNumber:itemModel.postId]) {
            index = idx;
            *stop = YES;
        }
    }];
    
    if (index != -1) {
        [self.dataArray removeObjectAtIndex:index];
        self.total--;
        if (self.dataArray.count == 0 && self.total != 0) {
            self.page++;
            [self loadDataSource];
        }else{
            if (self.dataArray.count != self.total) {
                [self.collectionView.mj_footer resetNoMoreData];
            }
            [self.collectionView reloadData];
        }
    }
}


- (void)loadDataSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"postId"] = self.userId;
    param[@"pageIndex"] = @(self.page);
    param[@"pageSize"] = @(10);
    param[@"tpye"] = @"2";
    param[@"checked"] = @(1);
    param[@"md5"] = [RPAppManager md5StrWithApi:GetUserPostList];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(GetUserPostList) parames:param success:^(id responseObj) {
        if ([self.collectionView.mj_footer isRefreshing]) {
            [self.collectionView.mj_footer endRefreshing];
        }
        if (self.page == 1) {
            self.dataArray = [HomePageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        }else{
            [self.dataArray addObjectsFromArray:[HomePageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
        }
        CGFloat bottom = self.collectionView.mj_insetB;
        if ([responseObj[RESPONSE][LASTPAGE] boolValue] || ![responseObj[RESPONSE][NEXTPAGE]boolValue]) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            if (self.collectionView.mj_footer.cl_height == 44.0f) {
                self.collectionView.mj_footer.cl_height = 138.0f;
                if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                    self.collectionView.mj_insetB = 138.0f;
                }
            }
        }else{
            [self.collectionView.mj_footer resetNoMoreData];
            if (self.collectionView.mj_footer.cl_height == 138.0f) {
                self.collectionView.mj_footer.cl_height = 44.0f;
                if (bottom == 138.0f) {
                    self.collectionView.mj_insetB = 44.0f;
                }
            }
        }
       
        self.total = [responseObj[RESPONSE][TOTAL] intValue];
        
        self.noDataView.hidden = self.dataArray.count > 0;
        
        [self.collectionView reloadData];
        
    } failure:^(id error) {
       
    }];
}

- (CGFloat)flowLayout:(UICollectionViewLayout *)layout heightForIndexPath:(NSIndexPath *)indexPath{
    
    HomePageItemModel *itemModel = self.dataArray[indexPath.item];
    
    CGFloat screenW = UIScreen.mainScreen.bounds.size.width;
    // 计算一半的宽度占比
    CGFloat itemW = (screenW - 3 * 5)/2;
    // 计算图片的高度3/4
    CGFloat imgH = itemW/3*4;
    
    CGSize textSize = [self getTextSizeWithText:itemModel.contentText font:font(12) maxSize:CGSizeMake(itemW - 16, MAXFLOAT)];
    
    if (itemModel.contentType.intValue == 1) {
        return imgH + 40;
    }else{
        if (itemModel.contentText.length == 0) {
            return imgH + 38;
        }else{
            CGFloat maxH = [self heightOfLines:2 font:font(12)];
            return imgH + MIN(ceil(textSize.height),maxH) + 12 + 34;
        }
    }
}
- (CGFloat)heightOfLines:(int)lines font:(UIFont *)font{
    if (lines <= 0) {
        return 0;
    }
    NSString *str = @"*";
    for (int index = 0; index < lines - 1 ; index++) {
        str = [str stringByAppendingString:@"\n*"];
    }
    NSDictionary *dict = @{NSFontAttributeName:font};
    
    CGSize size = [str sizeWithAttributes:dict];
    
    return ceil(size.height);
}

- (CGSize)getTextSizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize
{
    CGSize size = CGSizeZero;
    if(text == nil){
        text = @"";
    }
    if(font == nil){
        font = [UIFont systemFontOfSize:13];
    }
    NSDictionary *attribute = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
    size = [text boundingRectWithSize:maxSize options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    return size;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    self.collectionView.mj_footer.hidden = self.dataArray.count == 0;
    self.noDataView.hidden = self.dataArray.count > 0;
    return self.dataArray.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MinePageOpusListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MinePageOpusListCell" forIndexPath:indexPath];
    [cell setItemModel:self.dataArray[indexPath.item]];
    cell.delegate = self;
    return cell;
}


- (UIView *)listView {
    return self.view;
}

- (UIScrollView *)listScrollView {
    return self.collectionView;
}


- (void)listViewDidScrollCallback:(void (^)(UIScrollView *))callback {
    self.scrollCallback = callback;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    !self.scrollCallback ?: self.scrollCallback(scrollView);
   
}

#pragma mark - MinePageOpusListCellDelegate
- (void)showOpusDetailWithCurrentModel:(HomeTagItemModel *)itemModel{
   
    NSInteger index = [self.dataArray indexOfObject:itemModel];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[kXHItemType] = @(XHPageDetailItemTypeMix);
    param[kXHPlatformType] = @(XHPageDetailPlatformTypeUserList);
    param[kXHCurrentPage] = @(self.page);
    param[kXHCurrentIndex] = @(index);
    param[kXHShowUserInfo] = @(NO);
    param[kXHListSource] = self.dataArray;
    param[kXHUserCreateTime] = @(YES);
    HomePageDetailViewController *dtlVC = [[HomePageDetailViewController alloc]initWithConfigInfo:param];
    [self.navigationController pushViewController:dtlVC animated:YES];
}

@end
